import { fileURLToPath, URL } from 'node:url'
import fs from 'fs'
import { defineConfig, loadEnv } from 'vite'
import Components from 'unplugin-vue-components/vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { createHtmlPlugin } from 'vite-plugin-html'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import cesium from 'vite-plugin-cesium'

const resolvePath = (url: string) => {
  return fileURLToPath(new URL(url, import.meta.url))
}

const Base_URL = '/sa-gis-web/'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const isDev = ['development', 'test'].includes(mode)

  try {
    fs.copyFileSync(
      resolvePath(`./public/config/${mode}.js`),
      resolvePath(`./public/config/index.js`)
    )
  } catch (err) {
    console.log(err)
  }

  return {
    base: Base_URL,
    envPrefix: 'VUE_',
    plugins: [
      vue(),
      vueJsx(),
      cesium(),
      Components({
        // 指定组件位置，默认是src/components
        dirs: ['src/components'],
        // ui库解析器
        // resolvers: [ElementPlusResolver()],
        extensions: ['vue'],
        // 配置文件生成位置
        dts: 'src/components.d.ts'
      }),
      createHtmlPlugin({
        inject: {
          data: {
            ...env,
            timestamp: Date.now(),
            BASE_URL: isDev ? '/' : Base_URL
          }
        }
      }),
      createSvgIconsPlugin({
        iconDirs: [resolvePath('./src/assets/icons')],
        symbolId: 'icon-[dir]-[name]'
      })
    ],
    resolve: {
      alias: {
        '@': resolvePath('./src')
      }
    },
    server: {
      host: '0.0.0.0',
      port: 9100
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: id => {
            if (id.includes('env.config')) {
              return 'env.config'
            }
          }
        }
      }
    }
  }
})
